<!-- eslint-disable no-undef -->
<script setup lang="ts">
import { emitter } from '@/composables'
import { queryZdZdmcInfo, queryWzxxByQyIdAndBzLx } from '@/service/api'
import Header from '@/components/Header/index.vue'
import TabLeft from './TabLeft.vue'
import FactoryInfo from './components/FactoryInfo/index.vue'
import ProductionStorage from './components/ProductionStorage/index.vue'
import EnterpriseFacilities from './components/EnterpriseFacilities/index.vue'
import FireFightingFacilities from './components/FireFightingFacilities/index.vue'
import ProfessionalTeam from './components/ProfessionalTeam/index.vue'
import AzimuthAdjustment from './components/AzimuthAdjustment/index.vue'

/**************战时标绘组件 *****************/
import RightLayerManager from './components/FirefightPlot/RightLayerManager.vue'
import LayerOperationConfirm from './components/FirefightPlot/LayerOperationConfirm.vue'
import LeftFeatureControl from './components/FirefightPlot/LeftFeatureControl.vue'
import MeasureTool from './components/FirefightPlot/MeasureTool.vue'
import RightFeatureOperation from './components/FirefightPlot/RightFeatureOperation.vue'
import FireFightExportPlot from './components/FirefightPlot/FireFightExportPlot.vue'

/************* END ****************/
import TipsPage from '@/components/TipsPage/index.vue'
import FactorConfirm from '@/components/FactorConfirm/index.vue'
import FormCheckConfirm from '@/components/FormCheckConfirm/index.vue'

import { loadAllMapFactor, clearEditState, loadFeatureClick } from '@/utils/common/index'

const store = useChemicalStore()
let tileCenter: any

onMounted(() => {
  //请求模型保存数据
  queryMxdzInfo({ key: store.qyInfo.id }).then((res: any) => {
    if (res.length > 0) {
      if (res[0].mxsz) {
        store.qyInfo.mxdzInfoList[0].mxsz = JSON.parse(res[0].mxsz)
      } else {
        store.qyInfo.mxdzInfoList[0].mxsz = ''
      }
      localStorage.setItem('qyInfo', JSON.stringify(store.qyInfo))
    }
  })

  /** 加载倾斜摄影 */
  window.G3DTileSet.removeAll()
  let tileSet: any = null
  if (store.qyInfo.mxdzInfoList && store.qyInfo.mxdzInfoList.length > 0) {
    tileSet = window.G3DTileSet.add({
      name: store.qyInfo.id,
      option: {
        url: store.qyInfo.mxdzInfoList[0].url,
        //offsetHeight: 60,
      },
    })
  }
  if (tileSet) {
    tileSet = tileSet.getTileset()

    tileSet.readyPromise.then(() => {
      //笛卡尔坐标转经纬度坐标
      const ellipsoid = window.map3DControl.viewer.scene.globe.ellipsoid

      tileCenter = { ...tileSet.boundingSphere.center }

      const cartographic = ellipsoid.cartesianToCartographic(tileSet.boundingSphere.center)
      const lng = Cesium.Math.toDegrees(cartographic.longitude)
      const lat = Cesium.Math.toDegrees(cartographic.latitude)
      const alt = cartographic.height

      console.log({ lng, lat, alt })
      localStorage.setItem('modelOldWzxx', JSON.stringify({ tx: lng, ty: lat, tz: alt }))
      store.modelOldWzxx = JSON.parse(localStorage.getItem('modelOldWzxx'))

      store.tileSetOptions.tx = lng
      store.tileSetOptions.ty = lat
      store.tileSetOptions.tz = alt

      store.tileSetOptions.rz = 90
      update3dtilesMaxtrix(tileSet, store.tileSetOptions)

      if (store.qyInfo.mxdzInfoList[0].mxsz) {
        store.tileSetOptions = store.qyInfo.mxdzInfoList[0].mxsz
        // window.GCamera.flyTo({
        //   pos: {
        //     lng: store.tileSetOptions.tx,
        //     lat: store.tileSetOptions.ty,
        //     height: 1200,
        //   },
        // })
      } else {
        //定位到tileset集合处
        // window.map3DControl.viewer.zoomTo(tileSet, new Cesium.HeadingPitchRange(0, -1.5, 1200))
      }
      console.log(store.tileSetOptions, 'store.tileSetOptions')
    })
  }

  initData()
  // loadFeatureClick()
})

watch(
  () => store.tileSetOptions,
  (newVal, oldVal) => {
    if (!newVal.tx) {
      return
    }

    window.GCamera.flyTo({
      pos: {
        lng: newVal.tx,
        lat: newVal.ty,
        height: 1200,
      },
    })

    console.log(newVal, 'newVal.tx')

    const tileSet = window.G3DTilesetArray[0].tileSet.getTileset()

    // update3dtilesMaxtrix(tileSet, newVal)
    return

    //旋转1
    // const position = Cesium.Cartesian3.fromDegrees(newVal.tx, newVal.ty, newVal.tz)
    // const mtx = Cesium.Transforms.eastNorthUpToFixedFrame(position)
    // Cesium.Matrix4.multiplyByUniformScale(mtx, newVal.scale, mtx)

    // const mx = Cesium.Matrix3.fromRotationX(Cesium.Math.toRadians(45)) //绕x轴旋转
    // const rotationX = Cesium.Matrix4.fromRotationTranslation(mx)
    // Cesium.Matrix4.multiply(mtx, rotationX, mtx)

    // tileSet._root.transform = mtx

    //旋转2
    // const m = tileSet.modelMatrix
    // const m1 = Cesium.Matrix3.fromRotationZ(Cesium.Math.toRadians(45))
    // Cesium.Matrix4.multiplyByMatrix3(m, m1, m)
    // tileSet.modelMatrix = m

    //旋转3
    // const m = tileSet.modelMatrix
    // // RotateX为旋转角度，转为弧度再参与运算
    // const rx = Cesium.Matrix3.fromRotationX(Cesium.Math.toRadians(45))
    // const ry = Cesium.Matrix3.fromRotationY(Cesium.Math.toRadians(45))
    // const rz = Cesium.Matrix3.fromRotationZ(Cesium.Math.toRadians(45))
    // // 矩阵计算
    // Cesium.Matrix4.multiplyByMatrix3(m, rx, m)
    // Cesium.Matrix4.multiplyByMatrix3(m, ry, m)
    // Cesium.Matrix4.multiplyByMatrix3(m, rz, m)
    // // 赋值
    // tileSet.modelMatrix = m

    //旋转4
    // const m = tileSet.modelMatrix
    // const mx = Cesium.Matrix3.fromRotationX(Cesium.Math.toRadians(45))
    // const rotate = Cesium.Matrix4.fromRotationTranslation(mx)
    // Cesium.Matrix4.multiply(m, rotate, m)
    // tileSet._root.transform = m

    //平移
    const cartographicCenter = Cesium.Cartographic.fromCartesian(tileCenter)
    const surface = Cesium.Cartesian3.fromRadians(
      cartographicCenter.longitude,
      cartographicCenter.latitude,
      cartographicCenter.height
    )
    const offset = Cesium.Cartesian3.fromDegrees(newVal.tx, newVal.ty, newVal.tz)
    const translation = Cesium.Cartesian3.subtract(offset, surface, new Cesium.Cartesian3())
    tileSet.modelMatrix = Cesium.Matrix4.fromTranslation(translation)
  },
  {
    // immediate: true,
    deep: true,
  }
)

//模型调整位置
const update3dtilesMaxtrix = (tileSet: any, params: any) => {
  //旋转
  // const rx = Cesium.Matrix3.fromRotationZ(Cesium.Math.toRadians(params.rx))
  // const ry = Cesium.Matrix3.fromRotationZ(Cesium.Math.toRadians(params.ry))
  const rz = Cesium.Matrix3.fromRotationZ(Cesium.Math.toRadians(params.rz))
  // const rotationX = Cesium.Matrix4.fromRotationTranslation(rx)
  // const rotationY = Cesium.Matrix4.fromRotationTranslation(ry)
  const rotationZ = Cesium.Matrix4.fromRotationTranslation(rz)

  //平移
  const position = Cesium.Cartesian3.fromDegrees(params.tx, params.ty, params.tz)
  const m = Cesium.Transforms.eastNorthUpToFixedFrame(position)

  //旋转、平移矩阵相乘
  // Cesium.Matrix4.multiply(m, rotationX, m)
  // Cesium.Matrix4.multiply(m, rotationY, m)
  Cesium.Matrix4.multiply(m, rotationZ, m)

  //比例缩放
  const scale = Cesium.Matrix4.fromUniformScale(params.scale)
  Cesium.Matrix4.multiply(m, scale, m)

  //赋值给tileset
  tileSet._root.transform = m
}

const tabIndex = ref(0)
const tabClick = (id: any) => {
  if (id !== 5) {
    //请求模型保存数据
    queryMxdzInfo({ key: store.qyInfo.id }).then((res: any) => {
      if (res.length > 0) {
        if (res[0].mxsz) {
          store.qyInfo.mxdzInfoList[0].mxsz = JSON.parse(res[0].mxsz)
          store.tileSetOptions.tx = store.qyInfo.mxdzInfoList[0].mxsz.tx
          store.tileSetOptions.ty = store.qyInfo.mxdzInfoList[0].mxsz.ty
          store.tileSetOptions.tz = store.qyInfo.mxdzInfoList[0].mxsz.tz
        } else {
          store.qyInfo.mxdzInfoList[0].mxsz = ''
          store.tileSetOptions.tx = store.modelOldWzxx.tx
          store.tileSetOptions.ty = store.modelOldWzxx.ty
          store.tileSetOptions.tz = store.modelOldWzxx.tz
        }
        localStorage.setItem('qyInfo', JSON.stringify(store.qyInfo))

        window.GCamera.flyTo({
          pos: {
            lng: store.tileSetOptions.tx,
            lat: store.tileSetOptions.ty,
            height: 1200,
          },
        })
      }
    })
  }

  clearEditState() //清除标注状态
  store.closeAllPSDialog() //关闭全部弹窗
  tabIndex.value = id

  /******* 进入企业作战图层管理 ***************/
  if (id === 6) {
    firefightPlotStore.isLayerControlFlag = true
  } else {
    firefightPlotStore.isLayerControlFlag = false
  }
}

//保存标注类型字典项
queryZdZdmcInfo({ key: 'bzlx' }).then((res: any) => {
  store.bzlxList = res
})

const qyId = computed(() => {
  return store.qyInfo.id
})

/** 数据初始化 */
function initData() {
  clearEditState() //清除标注状态

  /** 进入系统移除全部要素 */
  window.GOverlay.removeAll()
  window.GScrollWall.removeAll()
  window.GPoint.removeAll()
  window.GCgsRect.removeAll()

  /** 查询全部地图要素 */
  queryWzxxByQyIdAndBzLx({ qyid: store.qyInfo.id }).then((res: any) => {
    loadAllMapFactor(res)
  })
}

/******* 战时标绘逻辑 START *********** */
const firefightPlotStore = useFirefightPlotStore()

/******* 战时标绘逻辑 END *********** */
</script>

<template>
  <Header />

  <!-- 左侧tab -->
  <TabLeft v-if="!firefightPlotStore.isFirefightPlotFlag" @tabClick="tabClick" />
  <!-- 标绘要素提示标牌 -->
  <TipsPage v-if="store.tipsPageShow" />

  <div v-show="!firefightPlotStore.isLayerControlFlag">
    <!-- 企业信息 -->
    <FactoryInfo v-if="tabIndex === 0" />

    <!-- 生产存储 -->
    <ProductionStorage v-if="tabIndex === 1" />

    <!-- 消防设施 -->
    <FireFightingFacilities v-if="tabIndex === 2" />

    <!-- 消防设施 -->
    <EnterpriseFacilities v-if="tabIndex === 3" />

    <!-- 企业专职队 -->
    <ProfessionalTeam v-if="tabIndex === 4" />

    <!-- 模型设置 -->
    <AzimuthAdjustment v-if="tabIndex === 5" />

    <!-- 要素保存二次确认弹窗 -->
    <FactorConfirm />

    <!-- 校验表单是否为空弹窗 -->
    <FormCheckConfirm />
  </div>

  <!--  战时标绘组件 START-->
  <div v-show="firefightPlotStore.isLayerControlFlag">
    <!-- 右侧 标绘图管理页面 -->
    <RightLayerManager v-if="!firefightPlotStore.isFirefightPlotFlag" />
    <!-- 左侧 测量工具面板 -->
    <MeasureTool />
    <!-- 新增编辑图层 弹窗 -->
    <LayerOperationConfirm v-if="firefightPlotStore.layerOperationConfirmData" />
    <!-- 左侧 符号属性面板 -->
    <LeftFeatureControl
      v-if="firefightPlotStore.isFirefightPlotFlag && firefightPlotStore.isLeftPropertyEditFlag"
    />
    <!-- 右侧 标绘面板 -->
    <RightFeatureOperation v-if="firefightPlotStore.isFirefightPlotFlag" />

    <!-- 导出图 -->
    <FireFightExportPlot />
  </div>
  <!--  战时标绘组件 END-->
</template>

<style lang="less" scoped>
#cesiumContainer {
  position: absolute;
  padding: 0px;
  margin: 0px;
  width: 100vw;
  height: 100vh;
}
</style>
